package com.hp.bon.sgw.wh.channel.handler;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.hp.bon.sgw.Constants;
import com.hp.bon.sgw.bean.XmlMessage;
import com.hp.bon.sgw.core.BuzProcessorManager;
import com.hp.bon.sgw.core.CallParam;
import com.hp.bon.sgw.core.channel.SoapChannel;
import com.hp.bon.sgw.core.channel.handler.IAsynCallHandler;
import com.hp.bon.sgw.threads.TaskManager;
import com.hp.bon.sgw.wh.service.UserResourceConfigService;
import com.hp.bon.sgw.wh.utils.LogUtil;
import com.hp.ocs.diameter.DiameterUtils;
import com.hp.ocs.diameter.message.*;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.lang.StringUtils;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.simpleframework.http.Request;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName: QryPaymentHandle
 * @Description: 3.2.12.1缴费销帐记录查询API
 */
public class QryPaymentHandle implements IAsynCallHandler {
	private static final Logger _log = LoggerFactory.getLogger(QryPaymentHandle.class);

	private static final Object XmlMessage = null;
	private UserResourceConfigService userResourceConfigService ;
	private PrintStream printStream;
	private JSONObject requestObject;
	private int flag=0;//0 标识为旧流程
    private long startTime;
    private Request request;
	public QryPaymentHandle(PrintStream printStream, JSONObject requestObject, Request request, long startTime) {
		this.printStream = printStream;
		this.requestObject = requestObject;
        this.startTime = startTime;
        this.request = request;
	}

	@Override
	public int getProtocolType() {
		return 0;
	}

	@Override
	public void onCallResult(CallParam callParam) {
		XmlMessage ack = null;
		Object response = null;
		if (callParam.getResponse() != null) {
			_log.warn("getResponse():");
			response = callParam.getResponse();
		} else if (callParam.getRecvResponse() != null) {
			_log.warn("getRecvResponse():");
			response = callParam.getRecvResponse();
		}
		if (response == null) {
			int _retcodeTmp = callParam.getRetCode() == 3002 ? 11202 : callParam.getRetCode();
			ack = SoapChannel.createERRAnwser(callParam.getSessionId(), _retcodeTmp, callParam.getResultMsg());
			callParam.setServiceResultCode(_retcodeTmp);// 11203
		} else {
			if (response instanceof Message) {// CCA -> XML
				ack = BuzProcessorManager.getInstance().convertMessageToAck(callParam);
			} else if (response instanceof XmlMessage) {
				ack = (XmlMessage) response;
			} else {
				_log.warn("unknown response type:" + callParam.getResponse().getClass().getName());
			}
		}
		try {
			
			if (response instanceof Message) {
                _log.info("================response instanceof Message");
            }else if (response instanceof XmlMessage) {
                _log.info("================response instanceof XmlMessage");
            }
			String respXML = convertResponseString(response, callParam.getServiceResultCode());
			if("0".equals(respXML)){
			    return;
            }

			byte[] resp = respXML.getBytes("UTF-8");
			ack.setLength(resp.length);
			ack.setMsgTime(System.currentTimeMillis());
			printStream.write(resp);
			printStream.close();
			callParam.setResponse(ack);
            //记录到日志
            LogUtil.saveLogToABM(request,respXML,startTime);
			TaskManager.taskProcess(callParam);
            _log.info("http response(cfq) " + respXML);
		} catch (UnsupportedEncodingException e) {
			_log.info("convertResponseString UnsupportedEncodingException error,msg=" + e.getMessage());
		} catch (IOException e) {
			_log.info("convertResponseString IOException,msg=" + e.getMessage());
		}catch (Exception e) {
			e.printStackTrace();
			_log.error("convertResponseString IOException,msg=" + e.getMessage());
		}
	}
	

	
	
	/**
	 * 返回最终json格式数据
	 * @param answer
	 * @param serviceResultCode
	 * @return
	 */
	@SuppressWarnings("unchecked")
	private String convertResponseString(Object answer, int serviceResultCode) {
		_log.error("QryPaymentHandle serviceResultCode = {}", serviceResultCode);
        _log.info("===========service_result_code===============" + serviceResultCode);
        String response = "";
		Map<String, Object> data = new HashMap<String, Object>();
		Gson gson = new Gson();
		String areaCode;
        //调用新接口 走DCC
        String objType = requestObject.getJSONObject("svcObjectStruct").getString("objType");
        String objValue = requestObject.getJSONObject("svcObjectStruct").getString("objValue");
        String objAttr = requestObject.getJSONObject("svcObjectStruct").getString("objAttr");
        String dataArea = requestObject.getJSONObject("svcObjectStruct").getString("dataArea");
        if("2".equals(objAttr) || "6".equals(objAttr) || "027".equals(objValue.substring(0,3))){
            areaCode="027";
        }else{
            areaCode=objValue.substring(0,4);
        }
			// 调用webservice接口查询详单信息
            Element serviceInformation = DocumentHelper.createElement("Service_Information");
			    //2020-03-24 调用webservice改DCC
                _log.info("=======================鉴权完毕, 3.0 调用webservice改DCC==================");
            serviceInformation.addElement("Channel_Id").setText("0");
            serviceInformation.addElement("Area_Code").setText(areaCode);
            serviceInformation.addElement("DestinationAttr").setText(objAttr);
            serviceInformation.addElement("Destination_Id").setText(objValue);
            serviceInformation.addElement("Destination_Id_Type").setText("2");
            serviceInformation.addElement("Billing_Cycle").setText(requestObject.getString("billingCycleId"));
            XmlMessage req = new XmlMessage(true);
            String IP = request.getClientAddress().getAddress().getHostAddress();
            String tmallHostId = "SGWHBCFQ@027.ctnbc-bon.net";
            String sessionId = DiameterUtils.makeSessionID(tmallHostId);
            req.setIp(IP);
            req.setMsgTime(System.currentTimeMillis());
            req.setMID(sessionId);
            req.setUID(tmallHostId);
            req.setSCID("PaymentRecordQuery.jf3@027.ctnbc-bon.net");
            req.setSIG(null);
            req.setREPTAG(0);
            req.setDATA(serviceInformation.asXML());
            req.setDataElement(serviceInformation);
            // new CallParam对象
            QryPaymentHandle2 qryBillHandle = new QryPaymentHandle2(printStream, requestObject,request,startTime);
            CallParam callParam = new CallParam(req.getMID(), req.getSCID(), req, req.getUID(), qryBillHandle);
            BuzProcessorManager.getInstance().processRequest(callParam);
            return "0";
	}

	
	/**
	 * 处理CCA结果
	 * @param answer
	 * @return
	 */
	public Map<String, Object> getAvpsFromMessage(Message answer) {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			AVP avp = answer.find(Constants.DIAMETER_AVP_SERVICE_INFOMATION, Constants.DIAMETER_VENDOR_3GPP);
			AVP_Grouped avpServiceInfomation = new AVP_Grouped(avp);
			AVP[] avps = avpServiceInfomation.queryAVPs();
			for (AVP avpData : avps) {
				
				if (avpData.code() == 20631 && avpData.vendorID() == Constants.DIAMETER_VENDOR_CT) {
					map.put("Result", String.valueOf(new AVP_Unsigned32(avpData).queryValue()));
				}
				
				if (avpData.code() == 80615 && avpData.vendorID() == Constants.DIAMETER_VENDOR_CT) {
					map.put("HomeAreaCode", String.valueOf(new AVP_Unsigned32(avpData).queryValue()));
				}
				if (avpData.code() == 80411 && avpData.vendorID() == Constants.DIAMETER_VENDOR_CT) {
					map.put("Latn_Id", new AVP_UTF8String(avpData).queryValue());
				}

                if (avpData.code() == 50207 && avpData.vendorID() == Constants.DIAMETER_VENDOR_CT) {
                    map.put("Area_Code", new AVP_UTF8String(avpData).queryValue());
                }
				
			}
		} catch (Exception e) {
			map = null;
			_log.info("getAvpsFromMessage Exception error,msg=" + e.getMessage());
		}
		return map;
	}

	
	/**
	 * 调用详单查询webservice接口
	 * @param param
	 * @return
	 */
	private  String sendWebService(String param,String url) {
		_log.info("===========WebServiceProcessor url===============" + url);
		_log.info("===========WebServiceProcessor param===============" + param);
		String resp = "";
		PostMethod post = new PostMethod(url);
		try {
			RequestEntity requestEntity = new StringRequestEntity(param, "text/xml", "UTF-8");
			post.setRequestEntity(requestEntity);
			if(flag == 0) {
				post.setRequestHeader("SOAPAction", "text/xml; charset=utf-8");
			}
			HttpClient client = new HttpClient();
			client.getHttpConnectionManager().getParams().setConnectionTimeout(5 * 1000);
			client.getHttpConnectionManager().getParams().setSoTimeout(5000);
			client.executeMethod(post);
			resp = post.getResponseBodyAsString();
		} catch (UnsupportedEncodingException e) {
			_log.error("===========" + url + " call UnsupportedEncodingException===============", e);
		} catch (HttpException e) {
			_log.error("===========" + url + " call HttpException===============", e);
		} catch (IOException e) {
			_log.error("===========" + url + " call IOException===============", e);
		}
		_log.info("===========WebServiceProcessor resp===============" + resp);
		return resp;
	}
	/**
	 * 由于计费侧提供的接口协议没变，只是地址调整，割接到3.0的本地网需要调用新的地址
	 * 集团电子发票API接口调整
	 * 获取判断使用的地址
	 * jf3_flag 刷新开关  配置为1则表示启用割接地市判断，配置为0则表示按现有的流程
	 * Jf3_jt_latn_id  割接地市配置项（多个地市用逗号分隔，如果配置项调整为888，则表示全部调用新地址）
	 * resultLanIdStr 区域编码
	 * cityId
	 * jf3_jt_latn_id 是84201这种
		jf3_latn_id是1001 1018 这种
		jf3_area_coee是027 0716 这种
		type 传参0 1001类 传1 84210类   返参 1 新 0 旧的
	 */
	private String getVersionType(String cityId,String type) {
		String jf3_flag = userResourceConfigService.getValue("jf3_flag","");////增加刷新开关  ,配置为1则表示启用割接地市判断，配置为0则表示按现有的流程
		String jf3_jt_latn_id = userResourceConfigService.getValue("jf3_jt_latn_id","");
		String jf3_latn_id = userResourceConfigService.getValue("jf3_latn_id","");
		String str;
		if("0".equals(type)) {
			//1001类型
			str = jf3_latn_id;
		}else {
			//84201 类型
			str = jf3_jt_latn_id;
		}
		//1 新流程  0 旧的流程
		if("1".equals(jf3_flag)) {
			if("888".equals(str)) {
				return "1";//新的
			}else {
				String[] split_jt_latn_id = str.split(",");
				for (String string : split_jt_latn_id) {
					if(string.equals(cityId)) {
						//包含,仅区分新旧
						return "1";//新的 Recharged.jf3@027.ctnbc-bon.net
					}
				}
			}
			
		}
		return "0";//旧的 SeverRecharge.SGWPAY@027.ctnbc-bon.net  
	}

    /**
     * 处理paymentChannel 字段为空 ,并且转换为 Long类型
     * @return
     */
    private static String getResult(String gsonString){
        JSONObject jsonObject=JSONObject.parseObject(gsonString);
        JSONArray jsonArray=jsonObject.getJSONArray("paymentInfoList");
        if (jsonArray != null && !jsonArray.isEmpty()){
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject temp=jsonArray.getJSONObject(i);
                String paymentChannel=temp.getString("paymentChannel");
                if(StringUtils.isEmpty(paymentChannel) || "null".equals(paymentChannel)){
                    //paymentChannel 为空
                    temp.put("paymentChannel",7);
                }else{
                    temp.put("paymentChannel",Long.valueOf(paymentChannel));
                }
            }
        }
        return jsonObject.toJSONString();
    }


	public static void main(String[] args) {
//		String buildStringMes="\r\n" + 
//				"<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:web=\"http://webservice.asiainfo.com/\">\r\n" + 
//				"  <soapenv:Header/>\r\n" + 
//				"  <soapenv:Body>\r\n" + 
//				"    <web:qryPayment>\r\n" + 
//				"      <QryPaymentRequest>\r\n" + 
//				"        <billingCycleId>201909</billingCycleId>  \r\n" + 
//				"        <operAttrStruct>\r\n" + 
//				"          <staffId>1</staffId>\r\n" + 
//				"          <operOrgId>1</operOrgId>\r\n" + 
//				"          <operTime>20191106</operTime>\r\n" + 
//				"          <operPost>1</operPost>\r\n" + 
//				"          <operServiceId>1</operServiceId>\r\n" + 
//				"          <lanId>842011</lanId>\r\n" + 
//				"        </operAttrStruct>\r\n" + 
//				"        <svcObjectStruct> \r\n" + 
//				"          <objType>3</objType>\r\n" + 
//				"          <objValue>18972140850</objValue>\r\n" + 
//				"          <objAttr>2</objAttr>\r\n" + 
//				"          <dataArea>1</dataArea>\r\n" + 
//				"        </svcObjectStruct>\r\n" + 
//				"      </QryPaymentRequest>\r\n" + 
//				"    </web:qryPayment>\r\n" + 
//				"  </soapenv:Body>\r\n" + 
//				"</soapenv:Envelope>";
//		String resp = sendWebService(buildStringMes,"http://133.0.209.70:7100/bossws/soap/billing?wsdl");
//		XStream xstream2 = new XStream(new DomDriver());
//		xstream2.alias("QryPaymentResponse", QryPaymentResponse.class);
//		
//		xstream2.alias("paymentInfoList", QryPaymentResponse.PaymentInfoList.class);
//		xstream2.addImplicitCollection( QryPaymentResponse.class, "paymentInfoList");//隐式集合 隐藏
//		
//		xstream2.alias("accNbrDetailList", QryPaymentResponse.PaymentInfoList.AccNbrDetail.class);
//		xstream2.addImplicitCollection( QryPaymentResponse.PaymentInfoList.class, "accNbrDetailList");//隐式集合 隐藏
//		xstream2.autodetectAnnotations(true);
//		//resp = getRespString(resp);
//		QryPaymentResponse qryPaymentResponse = null;
//		qryPaymentResponse = (QryPaymentResponse) xstream2.fromXML(resp.substring(resp.indexOf("<QryPaymentResponse"), resp.indexOf("</ns1:qryPaymentResponse>")));
//		System.out.println(qryPaymentResponse.getResultCode());
	}
	
}
